# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                        di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdmCollect.

#    OdmCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdmCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.


import preEnv
# leggiamo da preEnv che è anche un file di configurazioni pre-environment

pg3 = preEnv.pg3_cla
aziendaforce = preEnv.aziendaforce
tipodbforce = preEnv.tipodbforce
hostdbforce = preEnv.hostdbforce
dbforce = preEnv.dbforce
web = preEnv.web
echosa = preEnv.echo
debugFilter = preEnv.debugFilter
debugDao = preEnv.debugDao

if web:
    main_conf = preEnv.main_conf_force
    preEnv.conf = main_conf

from lib.config import Config

import os
import sys
import shutil
import decimal
try:
    import psycopg2
    psycopg2.extensions.register_adapter(decimal.Decimal,
                                                psycopg2._psycopg.Decimal)
except:
    pass
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.exc import *
from sqlalchemy.engine import reflection
from sqlalchemy.event import listen
from sqlalchemy.pool import NullPool
from sqlalchemy.schema import CreateSchema
from sqlalchemy.ext.automap import automap_base

from EnvUtils import *

PRODOTTO = "OdCollect"
VERSIONE = "OdCollect 0.0.2"
conf = None
exceptionHandler = None
connection = None
modules_folders = []
new_print_enjine = True

import sys
print " QUALE DIR", sys.path[0] +"/"

SRC_PATH = sys.path[0]
#SRC_PATH = "/home/promo/odmc/"
STATIC_PATH = os.path.join(SRC_PATH, 'tpl')
IMAGE_PATH = os.path.join(SRC_PATH, 'img')
SESSION_DIR = os.path.join(SRC_PATH, 'session')
CACHE_DIR = os.path.join(SRC_PATH, 'cache')
URL_CHARS = 'abcdefghijkmpqrstuvwxyzABCDEFGHIJKLMNPQRST23456789'
COOKIENAME = "odcollect"
ALLOWED_SCHEMES = frozenset(['http', 'https', 'ftp', 'ftps'])

modulesList = []

confList = []
configDir = None

tipodb = main_conf.Database.tipodb
host = main_conf.Database.host
database = main_conf.Database.database
port = main_conf.Database.port
user = main_conf.Database.user
password = main_conf.Database.password
preEnv.port = port
preEnv.user = user
preEnv.password = password
preEnv.database = database
preEnv.host = host
preEnv.tipodb = tipodb
userdata = ["", "", "", user]
req = None
def handleEngine():
    engine = None
    print "TIPO DB",tipodb
    if tipodb == "sqlite":
        azienda = None
        mainSchema = None

        engine = create_engine("sqlite:///" + main_conf.Database.sqlitedb, encoding='utf-8', proxy=MyProxy())
        listen(engine, 'connect', my_on_connect)
    elif tipodb =="postgresql":
        from EnvUtils import *
        mainSchema = None
        engine = psycopg2new()

    if not engine:
        raise RuntimeError("Non è stato trovato possibile creare un ENGINE per il DB")
    engine.echo = echosa
    #engine.echo = True
    return engine

engine = handleEngine()
insp = reflection.Inspector.from_engine(engine)
print "QUESTI SONO GLI SCHEMI", insp.get_schema_names()
tipo_eng = engine.name
session = scoped_session(lambda: create_session(engine, autocommit=False))

meta = MetaData(engine)
meta.reflect(schema="main")

if tipo_eng=="sqlite" or tipo_eng=="mysql":
    mainSchema = None
    #schema = None
else:
    mainSchema = "main"
    #schema = None
if tipo_eng == "postgresql":
    try:
        engine.execute(CreateSchema("main"))
    except:
        pass
        #print "CREAZIONE SCHEMA Main NON RIUSCITO O GIA ESISTENTE"

if tipodb == 'postgresql':
    #if schema:
        #fk_prefix = schema + '.'
    #else:
        #fk_prefix = None
    fk_prefix_main = mainSchema  +'.'
else:
    fk_prefix = ""
    fk_prefix_main = ""

sch = None
census = False
#from data.tipoEnte import t_tipo_ente
#from data.ente import t_ente
#enti = session.query(t_ente).all()
#ee = [e.denominazione_breve.lower().replace(" ","") for e in enti]
#for e in ee:
    #try:
        #engine.execute(CreateSchema(e))
    #except:
        #print "CREAZIONE SCHEMA e NON RIUSCITO O GIA ESISTENTE"
#for e in insp.get_schema_names():
    #if e != "public" and e != "information_schema":
        #print " CARiCO NEL META LO SCHEMA", e
        #meta.reflect(engine)
#Base = automap_base(metadata=meta)
#Base.prepare()

#print "BOOOOOOOOOOOOOOOOOOOOOOOO"
#for a in Base.classes.items():
    #print a
